<template>
  <FullPageModal v-model:visible="innerVisible" :title="t('aiot.role.addRole')" :custom-footer="true">
    <div class="h-full flex flex-col">
      <div class="flex items-center justify-center mb-8">
        <steps :current="curStep" :data="stepData"> </steps>
      </div>
      <div ref="contentRef" class="flex-1 mx-0 md:mx-16 lg:mx-28 xl:mx-36 xxl:mx-48 overflow-auto">
        <div v-show="curStep === 0">
          <DynamicForm ref="dyForm" :model="innerModel" :model-form-setting="modelFormSetting" :force-column="true" />
        </div>
        <div v-show="curStep === 1">
          <SelectApps
            v-if="isEnterprise"
            ref="selectAppsRef"
            v-model:value="selectedApps"
            class="mb-4.5"
            :required="true"
          ></SelectApps>
          <AuthList
            v-model:value="authValue"
            :is-update="authListIsUpdate"
            :server-value="serverValue"
            :required-mark="true"
          />
          <div v-if="authErrMes" class="text-color-danger mt-2"> {{ authErrMes }} </div>
        </div>
        <div v-show="curStep === 2" v-if="!hideUser">
          <div class="flex flex-row items-center mb-3">
            <div class="flex-1 text-xl text-color-main">
              <span class="font-semibold align-middle">添加成员</span>
              <span class="text-color-danger ml-1.5 align-middle">*</span>
            </div>
            <div>
              <a-button type="link" @click="addUser"> <Icon type="icon-tianjia" /> {{ t("aiot.user.add") }} </a-button>
            </div>
          </div>
          <UserSelect
            ref="userSelect"
            v-model:value="selUserIds"
            :exclude-role-ids="excludeRoleIds"
            :class="[userErrMes ? ' border-color-danger' : ' border-color-split']"
            :handle-user="handleUser"
            :is-user-disable="(item) => !!item.isSystem"
          />
          <div v-if="userErrMes" class="text-color-danger mt-4.5">
            {{ userErrMes }}
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <template v-if="curStep === 0">
        <a-button @click="innerVisible = false">取消</a-button>
        <a-button type="primary" @click="handleContinue">继续</a-button>
      </template>
      <template v-else-if="curStep < stepData.length - 1">
        <a-button @click="handleBack">返回</a-button>
        <a-button type="primary" @click="handleContinue">继续</a-button>
      </template>
      <template v-else>
        <a-button @click="handleBack">返回</a-button>
        <a-button @click="ok(false)">确定</a-button>
        <a-button v-if="!hideUser" type="primary" @click="ok(true)">确定并继续新增</a-button>
      </template>
    </template>
    <CURDDialog
      ref="curdDialogForm"
      :create-title="t('aiot.user.add')"
      :show-options="showOptions"
      :model="userModel"
      :model-form-setting="userModelFormSetting"
      :curd="curd"
      id-key="userId"
      :reload-table="reloadUserSelect"
    />
    <LocationDialog v-model:visible="locDgVisible" @ok="chooseLoc" />
  </FullPageModal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import Icon from "/@/components/Icon.vue";
import Panel from "/@/components/Panel.vue";
import { nextTick, ref, shallowRef, watch } from "vue";
import UserSelect from "/@/components/UserSelect.vue";
import type { AuthorizedRoleFunctionsParams, RoleItem } from "/@/api/aiot/role/models";
import FullPageModal from "/@/components/FullPageModal.vue";
import { addRole } from "/@/api/aiot/role";
import { CURDAction, DynamicFormExpose, FormItemData, ShowCURDModalOptions } from "/@/components/CURDDialog/models";
import type { UserItem, UserSearchModel } from "/@/api/aiot/user/models";
import { Api as userApi } from "/@/api/aiot/user";
import { useCURD } from "/@/hooks/useCURD";
import { UserSelectExpose } from "/@/types/components";
import { useUserModel } from "/@/components/pages/User/useUserModel";
import { message } from "ant-design-vue";
import { AiotSubApp } from "/@/base/data";

const { t } = useI18n();
const props = defineProps<{
  visible: boolean;
  model: RoleItem;
  modelFormSetting: FormItemData[];
  isEnterprise?: boolean;
  hideUser?: boolean;
  excludeRoleIds: string;
  handleUser?: (userItem: UserItem) => void;
}>();
const emits = defineEmits(["create", "update:visible"]);
const innerVisible = ref(false);
watch(
  () => props.visible,
  (v) => {
    innerVisible.value = v;
  }
);
//第一次打开
let firstShow = true;
watch(innerVisible, (v) => {
  emits("update:visible", v);
  if (firstShow) {
    firstShow = false;
  }
  if (!v) {
    reset();
  }
});
//用于触发清空权限值逻辑
const serverValue = ref([]);
function reset() {
  curStep.value = 0;
  if (dyForm.value) {
    dyForm.value.resetFields();
  }
  selUserIds.value = [];
  authValue.value = {
    roleFolderPermissions: [],
    roleMenuPermissions: [],
  };
  serverValue.value = [];
  if (userSelect.value) {
    userSelect.value.reset();
  }
  selectedApps.value = [];
}
/**
 * steps
 */
const contentRef = shallowRef<HTMLDivElement>();
const curStep = ref(0);
const _stepData = [{ title: "角色信息填写" }, { title: "权限设置" }];
if (!props.hideUser) {
  _stepData.push({
    title: "添加用户角色成员",
  });
}
const stepData = ref(_stepData);
function validateApp(callback: () => void) {
  if (selectAppsRef.value) {
    selectAppsRef.value.validate().then(() => {
      validateAuth(callback);
    });
  } else {
    validateAuth(callback);
  }
}
function validateAuth(callback: () => void) {
  if (authListIsUpdate.value && authValue.value.roleMenuPermissions?.length === 0) {
    authErrMes.value = "请设置权限";
    nextTick(() => {
      if (contentRef.value) {
        contentRef.value.scrollTop = 9999;
      }
    });
    return;
  }
  callback();
}
function handleContinue() {
  if (curStep.value === 0) {
    if (dyForm.value) {
      dyForm.value.validate().then(() => {
        curStep.value++;
      });
    }
  } else if (curStep.value === 1) {
    validateApp(() => {
      curStep.value++;
    });
  }
}
function handleBack() {
  curStep.value--;
}
function ok(isContinue) {
  if (!props.hideUser && selUserIds.value.length === 0) {
    userErrMes.value = t("aiot.role.plzSelUser");
    return;
  }
  if (props.hideUser) {
    validateApp(() => {
      handleAddRole(isContinue);
    });
  } else {
    handleAddRole(isContinue);
  }
}
async function handleAddRole(isContinue) {
  if (!authListIsUpdate.value) {
    //没勾选后台
    authValue.value = {
      roleFolderPermissions: [],
      roleMenuPermissions: [],
    };
  }
  const result = await addRole({
    roleUsers: selUserIds.value,
    ...authValue.value,
    ...innerModel.value,
    applicationPermissions: props.isEnterprise ? selectedApps.value : [],
  });
  if (result) {
    emits("create");
    message.success("操作成功");
    if (isContinue) {
      reset();
    } else {
      innerVisible.value = false;
    }
  }
}
/**
 * 用户信息填写
 */
const dyForm = ref<DynamicFormExpose>();
const innerModel = ref<RoleItem>({ ...props.model });
/**
 * 权限设置
 */
const selectedApps = ref<AiotSubApp[]>([]);
const selectAppsRef = ref();
const authErrMes = ref("");
const authValue = ref<AuthorizedRoleFunctionsParams>({
  roleFolderPermissions: [],
  roleMenuPermissions: [],
});
//企业：一开始 没有勾选应用，所以不能编辑权限
//平台：能编辑权限
const authListIsUpdate = ref(!props.isEnterprise);
let lastHasAiot = false;
watch(
  selectedApps,
  (apps) => {
    if (!props.isEnterprise) {
      authListIsUpdate.value = true;
      return;
    }
    const hasAiot = apps.includes(AiotSubApp.AIOT);
    if (hasAiot) {
      authListIsUpdate.value = true;
    } else {
      if (lastHasAiot) {
        authValue.value = {
          roleFolderPermissions: [],
          roleMenuPermissions: [],
        };
      }
      authListIsUpdate.value = false;
    }
    lastHasAiot = hasAiot;
  },
  { deep: true }
);
watch(
  authValue,
  () => {
    authErrMes.value = "";
  },
  { deep: true }
);
/**
 * 添加用户角色成员
 */
const selUserIds = ref<string[]>([]);
const userSelect = ref<UserSelectExpose>();
const userErrMes = ref("");
watch(selUserIds, (v) => {
  if (v.length > 0) {
    userErrMes.value = "";
  }
});
function addUser() {
  showOptions.value = { action: CURDAction.CREATE };
}
function reloadUserSelect() {
  if (userSelect.value) {
    userSelect.value.reload();
  }
}
const showOptions = ref<ShowCURDModalOptions>();
const { curd } = useCURD<UserItem, UserSearchModel>({
  createUrl: userApi.addUser,
  getPageUrl: userApi.usersPage,
  updateUrl: userApi.updateUser,
  loadOnMounted: false,
});
const { userModel, userModelFormSetting, locDgVisible, chooseLoc, curdDialogForm } = useUserModel({
  isPlatform: !props.isEnterprise,
});
</script>
